//
//  CartoonSetViewController.m
//  Cartoon
//
//  Created by dllo on 15/10/28.
//  Copyright © 2015年 YSZ. All rights reserved.
//

#import "CartoonSetViewController.h"
#import "CartoonSetTableViewCell.h"
#import <LocalAuthentication/LocalAuthentication.h>
#import "MyViewController.h"
@interface CartoonSetViewController ()<UITableViewDataSource,UITableViewDelegate,CartoonSetTableViewCellDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSArray *array;
@end

@implementation CartoonSetViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.array = @[@"清除缓存",@"关于我们"];
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, SelfViewWidth, SelfViewHeight - 64 - 49) style:UITableViewStylePlain];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    [self.view addSubview:_tableView];
    [_tableView registerClass:[CartoonSetTableViewCell class] forCellReuseIdentifier:@"cell"];
    _tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SelfViewWidth, 200*HEIGHT)];
    UIImageView *image = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"11"]];
    image.frame = CGRectMake(0, 0, SelfViewWidth, 200 *HEIGHT);
    
    [_tableView.tableHeaderView addSubview:image];
    
    _tableView.bounces = NO;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.array.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    CartoonSetTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
//    if (indexPath.row == 0) {
//        cell.delegate = self;
//        cell.mySwitch.hidden = NO;
//    }
    cell.myLabel.text = self.array[indexPath.row];
    
    return cell;
}
- (void)switchTouchID:(UITableViewCell *)cell
{
    CartoonSetTableViewCell *myCell = (CartoonSetTableViewCell *)cell;
    LAContext *context = [[LAContext alloc]init]; //
    context.localizedFallbackTitle = @"TouchID";
    
    NSError *error = nil;
    
    // 判断支持 Touch ID
    // LAPolicy只有一个值: LAPolicyDeviceOwnerAuthenticationWithBiometrics
    if ([context canEvaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics error:nil]) {
        
        // 验证身份
        [context evaluatePolicy:LAPolicyDeviceOwnerAuthenticationWithBiometrics localizedReason:NSLocalizedString(@"登录", nil) reply:^(BOOL success, NSError *error) {
            if (success) {
                NSLog(@"TouchID deblocking success");
                if (myCell.mySwitch.on) {
                    [self showInfoWithmessage:@"设置加密成功" cell:cell];
                }else{
                    [self showInfoWithmessage:@"取消加密成功" cell:cell];
                }
            }
            else{
                if (error.code == kLAErrorUserFallback) {
                    NSLog(@"use passWord");
                    [self showInfoWithmessage:@"选择输入密码" cell:cell];
                }
                else if (error.code == kLAErrorUserCancel)
                {
//                    NSLog(@"cancel use TouchID");
//                    [self showInfoWithmessage:@"用户取消加密" cell:cell];
                    [myCell.mySwitch setOn:!myCell.mySwitch.on animated:YES];
                    [[FMDB shareFMDB].db executeUpdate:[NSString stringWithFormat:@"update cartoonset set myswitch = '%d' where myswitch = '%d'",myCell.mySwitch.on,!myCell.mySwitch.on]];
                    
                }
                // 不支持Touch ID 技术
                else
                {
                    NSLog(@"fail");
                    [self showInfoWithmessage:@"加密失败" cell:cell];
                }
            }
            
        }];
    }
    else
    {
        if (error.code == LAErrorTouchIDNotEnrolled) {
            [self showInfoWithmessage:@"未注册Touch ID" cell:cell];
        }
        else if (error.code == LAErrorPasscodeNotSet){
            [self showInfoWithmessage:@"未设置密码" cell:cell];
        }
        else{
            [self showInfoWithmessage:@"不支持Touch ID" cell:cell];
        }
    }
}
- (void)showInfoWithmessage:(NSString *)message cell:(UITableViewCell *)cell
{
    CartoonSetTableViewCell *myCell = (CartoonSetTableViewCell *)cell;
    if ([message isEqualToString:@"设置加密成功"] || [message isEqualToString:@"取消加密成功"] ) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:1];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
            NSString *hidd = [NSString stringWithFormat:@"%d",myCell.mySwitch.on];
            [[NSNotificationCenter defaultCenter] postNotificationName:@"lock" object:hidd];
        }];
        [alert addAction:okAction];
//        [self presentViewController:alert animated:YES completion:^{
//            
//        }];
    }else{
        [myCell.mySwitch setOn:!myCell.mySwitch.on animated:YES];
        [[FMDB shareFMDB].db executeUpdate:[NSString stringWithFormat:@"update cartoonset set myswitch = '%d' where myswitch = '%d'",myCell.mySwitch.on,!myCell.mySwitch.on]];
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:1];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDestructive handler:^(UIAlertAction *action) {
            

            
        }];
        [alert addAction:okAction];
        [self presentViewController:alert animated:YES completion:^{
            
        }];
    }
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    switch (indexPath.row) {
        case 0:{
            CGFloat size = [[SDImageCache sharedImageCache] getSize];
            NSString *str = [NSString stringWithFormat:@"%.2fM",size/1024/1024];
            UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"缓存" message:str delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"清除", nil];
            [alertView show];
        }
            
            break;
        case 1:
        {
            
            MyViewController *myVC = [[MyViewController alloc ]init];
            [self.navigationController pushViewController:myVC animated:NO];
        
            
        }
            break;
        case 2:
            break;
        default:
            break;
    }
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        [[SDImageCache sharedImageCache] clearDisk];
        
        NSString *cachPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
        
        NSArray *files = [[NSFileManager defaultManager] subpathsAtPath:cachPath];
        NSLog(@"files :%ld",[files count]);
        for (NSString *p in files) {
            NSError *error;
            NSString *path = [cachPath stringByAppendingPathComponent:p];
            if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
                [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
            }
        }
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
